package com.chapter1.basic.chain;

import java.util.Iterator;

/** 
 * @ClassName: MyChainQueue 
 * @Description:队列（链表实现）
 * @author minjun minjun@bw30.com
 * @date 2015-2-12 上午11:20:17 
 *  
 */
public class MyChainQueue<Item> implements Iterable<Item>{

	private Node first;
	
	private Node last;
	
	private int index;
	
	private class Node{
		
		Item item;
		
		Node next;
	}
	
	public boolean isEmpty(){
		return index==0;
	}
	
	public void enqueue(Item item){
		Node oldLast=last;
		last=new Node();
		last.item=item;
		last.next=null;
		if(isEmpty()){
			first=last;
		}else{
			oldLast.next=last;
		}
		index++;
	}
	
	public Item dequeue(){
		if(isEmpty()){
			throw new RuntimeException("没有元素了");
		}
		Item item=first.item;
		first=first.next;
		index--;
		return item;
	}

	@Override
	public Iterator<Item> iterator() {
		return new MyQueueIterator();
	}
	
	private class MyQueueIterator implements Iterator<Item>{
		
		private int i=index;
		
		private Node f=first;

		@Override
		public boolean hasNext() {
			return i>0;
		}

		@Override
		public Item next() {
			if(i==0){
				throw new RuntimeException("没有元素了...");
			}
			i--;
			Item item=f.item;
			f=f.next;
			return item;
		}

		@Override
		public void remove() {
			
		}
		
	}
}
